package com.itstudio.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itstudio.portal.entity.*;
import com.itstudio.portal.entity.dto.ProjectAddDto;
import com.itstudio.portal.entity.dto.ProjectDto;
import com.itstudio.portal.entity.vo.MyProjectVo;
import com.itstudio.portal.entity.vo.PageVo;
import com.itstudio.portal.entity.vo.ProjectVo;
import com.itstudio.portal.entity.vo.SelectProjectVo;
import com.itstudio.portal.mapper.AuthInfoMapper;
import com.itstudio.portal.mapper.IndustryMapper;
import com.itstudio.portal.mapper.ProjectMapper;
import com.itstudio.portal.mapper.UserMapper;
import com.itstudio.portal.service.AuthInfoService;
import com.itstudio.portal.service.ProjectService;
import com.itstudio.portal.utils.BeanCopyUtil;
import com.itstudio.portal.utils.Const;
import com.itstudio.portal.utils.JwtUtil;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (Project)表服务实现类
 *
 * @author makejava
 * @since 2024-11-13 16:48:23
 */
@Service("projectService")
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Autowired
    JwtUtil jwtUtil;
    @Autowired
    ProjectMapper projectMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;
    @Autowired
    AuthInfoMapper authInfoMapper;
    @Autowired
    AuthInfoService authInfoService;

    @Autowired
    private IndustryMapper industryMapper;

    //添加项目
    @Override
    public RestResponse add(ProjectAddDto projectAddDto, HttpServletRequest request) {
        Project project = BeanCopyUtil.classVo(projectAddDto, Project.class);
        String token = request.getHeader("Authorization").substring(7);
        String id = jwtUtil.verifyToken(token);
        Long aLong = Long.valueOf(id);
        LambdaQueryWrapper<AuthInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuthInfo::getUserId,aLong);
        AuthInfo authInfo = authInfoMapper.selectOne(wrapper);
        String businessAddress = authInfo.getBusinessAddress();
//        String[] split = businessAddress.split(",");
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < split.length-1; i++) {
//            sb.append(split[i]);
//        }
//        project.setCategoryId(sb.toString());
        project.setCategoryId(businessAddress);
        project.setCode(authInfo.getIndustry());
        project.setUserId(aLong);
        save(project);
        redisTemplate.opsForHash().put(Const.PROJECT_VIEW_COUNT_KEY, project.getId().toString(), 0);
        return RestResponse.success();
    }
    //删除项目
    @Override
    public RestResponse delete(Long id) {
        removeById(id);
        redisTemplate.opsForHash().delete(Const.PROJECT_VIEW_COUNT_KEY, id.toString());
        return RestResponse.success();
    }




    //修改项目
    public RestResponse updateProject(ProjectAddDto projectAddDto,HttpServletRequest request){
        Project project = BeanCopyUtil.classVo(projectAddDto, Project.class);
        String token = request.getHeader("Authorization").substring(7);
        String id = jwtUtil.verifyToken(token);
        Long aLong = Long.valueOf(id);
        LambdaQueryWrapper<AuthInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AuthInfo::getUserId,aLong);
        AuthInfo authInfo = authInfoMapper.selectOne(wrapper);
        String businessAddress = authInfo.getBusinessAddress();
        String[] split = businessAddress.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < split.length-1; i++) {
            sb.append(split[i]);
        }
        project.setCategoryId(sb.toString());
        project.setCode(authInfo.getIndustry());
        project.setUserId(aLong);

        //如果调用修改之后一定是待审核的状态
        project.setStatus("0");
        //如果不存在就保存 存在就删除
        saveOrUpdate(project);
        return RestResponse.success();
    }

    @Override
    public RestResponse updateView(Long id) {
        redisTemplate.opsForHash().increment(Const.PROJECT_VIEW_COUNT_KEY, id.toString(), 1);
        return RestResponse.success();
    }
    //根据id查看具体的详情
    @Override
    public RestResponse getProjectById(Long id) {
        ProjectVo projectVos = projectMapper.selectProjectId(id);
        Integer viewCount = (Integer) redisTemplate.opsForHash().get(Const.PROJECT_VIEW_COUNT_KEY, id.toString());
        projectVos.setVisitCount(viewCount.longValue());
        String code = projectVos.getCode();
        String[] split = code.split(",");
        //根据projectVos的code 去查看所属行业信息
        //去行业表查出来行业信息
        LambdaQueryWrapper<Industry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Industry::getParentId,split[0]);
        queryWrapper.eq(Industry::getCategoryId,split[1]);
        Industry testIndustry = industryMapper.selectOne(queryWrapper);
        projectVos.setCode(testIndustry.getCategoryName());
        return RestResponse.success(projectVos);

    }

    @Override
    public RestResponse getList(ProjectDto projectDto) {
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getStatus,1);
        wrapper.like(StringUtils.hasText(projectDto.getProjectName()),Project::getProjectName,projectDto.getProjectName());
        wrapper.eq(StringUtils.hasText(projectDto.getCode()),Project::getCode,projectDto.getCode());
        wrapper.eq(StringUtils.hasText(projectDto.getCategoryId()),Project::getCategoryId,projectDto.getCategoryId());
        long count = count(wrapper);
        List<SelectProjectVo> list = projectMapper.getList(projectDto.getProjectName(),projectDto.getCode(),projectDto.getCategoryId());
        List<SelectProjectVo> collect = list.stream()
                .skip((projectDto.getPageNumber()-1)*projectDto.getPageSize())
                .limit(projectDto.getPageSize())
                .map(project -> {
                    Integer viewCount = (Integer) redisTemplate.opsForHash().get(Const.PROJECT_VIEW_COUNT_KEY, project.getId().toString());
                    if(viewCount != null)
                        project.setVisitCount(viewCount.longValue());
                    return project;
                })
                .collect(Collectors.toList());
        for (SelectProjectVo selectProjectVo : list) {
            String code = selectProjectVo.getCode();
            String[] split = code.split(",");
            //去行业表查出来行业信息
            LambdaQueryWrapper<Industry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Industry::getParentId,split[0]);
            queryWrapper.eq(Industry::getCategoryId,split[1]);
            Industry testIndustry = industryMapper.selectOne(queryWrapper);
            selectProjectVo.setIndustry(testIndustry.getCategoryName());


        }
        PageVo pageVo = new PageVo(collect, count);
        return RestResponse.success(pageVo);
    }

    @Override
    public RestResponse selectMyProject(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        String id = jwtUtil.verifyToken(token);
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getUserId,id);
        List<Project> projects = list(wrapper);
        List<MyProjectVo> myProjectVos = BeanCopyUtil.classListVo(projects, MyProjectVo.class);
        return RestResponse.success(myProjectVos);
    }
}
